<template>
  <div class="container">
    <div class="search-container">
      <div class="time-container">
      <div class="start-time" @click="handleShowSelectedDate(1)">{{ queryParams.startTime }}</div>
      <div class="line">至</div>
      <div class="end-time" @click="handleShowSelectedDate(2)">{{ queryParams.endTime }}</div>
      </div>
      <div class="dept-container" @click="deptShow=true">
        {{ deptName }} <div class="clear-btn" @click.stop="clearDept"><van-icon v-if="deptName!=='选择部门'" name="clear" /></div>
      </div>
    </div>
    <div class="list-container">
      <van-pull-refresh v-model="refreshing" v-model:loading="loading" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="getList"
        >
          <div class="row" v-for="item in list" :key="item.id" @click="handleDetail(item)">
            <div class="dept-name">
              <div class="dept-name-hd">
                <span>{{ item.nickName }} </span>
                <span style="font-weight: normal;color:#999;">({{ item.deptName }})</span>
              </div>
              <div class="dept-name-ft" v-if="userStore.userInfo.userId===item.userId">
                <van-icon name="arrow" />
              </div>
            </div>
            <div class="total-row"><span class="label">应录数量：</span>{{ item.allUser }}</div>
            <div class="total-row"><span class="label">已录数量：</span>{{ item.yilu }}
              <span class="t1" v-if="item.normalUser>0" @click.stop="handleView(item)">{{ item.normalUser }}</span>
              <span class="t2" v-if="item.recordingUser>0">{{ item.recordingUser }}</span></div>
            <div class="total-row"><span class="label">未录数量：</span><span>{{ item.weilu }}</span></div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>
    <van-action-sheet v-model:show="show" :title="null">
      <van-date-picker
        v-model="currentDate"
        title="选择日期"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="handleConfirmSelectDate"
        @cancel="handleCancelSelectDate"
      />
    </van-action-sheet>
    <van-popup v-model:show="deptShow" round position="bottom" @close="handleCloseDept">
      <van-cascader
        v-model="queryParams.deptId"
        title="请选择所在地区"
        :options="deptOptions"
        :field-names="{text:'label',value:'id'}"
        @close="deptShow = false"
        @finish="confirmDept"
        @change="handleChangeDept"
      />
    </van-popup>
  </div>
</template>

<script setup>

import { computed, onMounted, reactive, ref, toRaw } from 'vue'
import { getCountByTimeApi } from '@/api/workLog.js'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import useUserStore from '@/stores/user.js'
import user from '@/stores/user.js'
import { deptTreeApi } from '@/api/user.js'

const show = ref(false)
const deptShow = ref(false)
const title = ref('选择日期')
const queryParams = reactive({
  startTime: dayjs().subtract(1, 'month').format('YYYY-MM-DD'),
  endTime: dayjs().format('YYYY-MM-DD'),
  deptId:''
})
const deptOptions = ref([])
const list = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const currentDate = ref(dayjs().format('YYYY-MM-DD').split('-'))
const minDate = ref(new Date(dayjs().subtract(1, 'year').format('YYYY-MM-DD')))
const maxDate = ref(new Date(dayjs().format('YYYY-MM-DD')))
const dateType = ref(1)
const deptName = ref('选择部门')
const router = useRouter()
const userStore = useUserStore()

const clearDept = () => {
  deptName.value = '选择部门'
  queryParams.deptId = ''
  getList()
}
const handleChangeDept = ({ selectedOptions,value })=>{
  queryParams.deptId = value
  deptName.value = selectedOptions[selectedOptions.length-1].label;
}
const confirmDept = ({ selectedOptions }) => {
  deptShow.value = false;
  deptName.value = selectedOptions[selectedOptions.length-1].label;
};
const handleCloseDept = ()=>{
  getList()
}

const handleDetail = (row) => {
  if (userStore.userInfo.userId === row.userId) {
    router.push(`/myWorkLog1`)
  }
}
const handleView = (row)=>{
  console.log(row)
  router.push(`/myWorkLog3?nickName=${row.nickName}&userId=${row.userId}&startTime=${queryParams.startTime}&endTime=${queryParams.endTime}`)
}

const handleConfirmSelectDate = (e) => {
  if (dateType.value === 1) {
    queryParams.startTime = e.selectedValues.join('-')
  } else if (dateType.value === 2) {
    queryParams.endTime = e.selectedValues.join('-')
  }
  show.value = false
  getList()
}
const handleCancelSelectDate = () => {
  show.value = false
}
const handleShowSelectedDate = type => {
  if (type === 1) {
    // 选择开始时间
    title.value = '选择开始日期'
    show.value = true
    // 最小值为本年度第一天
    currentDate.value = dayjs(queryParams.startTime).format('YYYY-MM-DD').split('-')
  } else if (type === 2) {
    // 选择结束时间
    title.value = '选择结束日期'
    show.value = true
    currentDate.value = dayjs(queryParams.endTime).format('YYYY-MM-DD').split('-')
  }
}

const getList = () => {

  let params = toRaw(queryParams)
  getCountByTimeApi(toRaw(params)).then(res => {
    if (refreshing.value) {
      list.value = []
      refreshing.value = false
    }
    list.value = res.data.map(item => {
      item.yilu = item.normalUser + item.recordingUser// 已经录入数
      item.weilu = item.allUser - item.yilu // 未录数
      return item
    })
    loading.value = false
    finished.value = true
  })
}

const onRefresh = () => {
  // 清空列表数据
  finished.value = false
  // 将 loading 设置为 true，表示处于加载状态
  loading.value = true
  getList()
}
const getDeptTree = () => {
  deptTreeApi().then(res=>{
    if(res.data && res.data.length){
      deptOptions.value = res.data
    }
  })
}
const init = () => {
  // getList()
  getDeptTree()
}

onMounted(() => {
  init()
})
</script>

<style scoped lang="less">
.container {
  width: 100vw;
  height: 100%;

  .search-container {
    width: 100%;
    background-color: #fff;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    .time-container{
      width: 60%;
      display: flex;
      align-items: center;
      justify-content: center;
      padding:0 5px;
      box-sizing: border-box;
      .start-time, .end-time {
        text-align: center;
      }
      .line{
        margin:0 5px;
      }
    }
    .dept-container{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40%;
      padding:0 5px;
      box-sizing: border-box;
      .clear-btn{
        display: inline-block;
        margin-left: 5px;
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        color:#999;
      }
    }
  }

  .list-container {
    margin-top: 10px;
    height: calc(100% - 60px);
    overflow-y: auto;

    .row {
      width: calc(100% - 20px);
      border-radius: 5px;
      background-color: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      margin: 5px auto;
      padding: 10px;
      box-sizing: border-box;

      .dept-name {
        height: 30px;
        line-height: 30px;
        font-weight: bold;
        border-bottom: 1px solid #f2f2f2;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .dept-name-hd{
          flex:1;
        }
        .dept-name-ft{
          width: 30px;
          height: 30px;
          display: flex;
          align-items: center;
          justify-content: center;
          color:#999;
        }
      }

      .total-row {
        font-size: 14px;
        line-height: 30px;
        display: flex;
        align-items: center;

        .label {
          color: #999;
        }

        .t1, .t2 {
          padding: 0 10px;
          color: #fff;
          border-radius: 2px;
          margin-left: 10px;
          line-height: 14px;
        }

        .t1 {
          background-color: green;
        }

        .t2 {
          background-color: orange;
        }
      }
    }
  }
}
</style>
